<template>
  <l-layout class="l-tab-page" v-if="!lr_loadPage">
    <template #left>
      <l-panel :title="$t('文件源')" style="padding-right: 0">
        <el-tree ref="sourceTree" class="learun-tree" v-loading="treeLoading" :data="treeData" default-expand-all
          :expand-on-click-node="false" @node-click="handleNodeClick" node-key="id">
          <span class="lr-tree-node" slot-scope="{ data }">
            {{ $t(data.name) }}
          </span>
        </el-tree>
      </l-panel>
    </template>
    <l-panel style="padding-left: 0">
      <template #toolLeft>
        <l-query2
          :items="queryItems"
          :formData="queryData"
          :loading="tableLoading"
          @search="handleSearch"
        >
          <template #name>
            <el-input v-model="queryData.name" :placeholder="$t('请输入文件名')" />
          </template>
        </l-query2>
      </template>
      <template #toolRight>
        <l-tool-btns
          :hasTableSetting="true"
          :hasAdd="false"
          btnText="上传文件"
          btnIcon="el-icon-upload"
          @setting="lr_handleSettingTable"
          @click="handleAdd()"
        >
          <l-excel-btns></l-excel-btns>
          <l-fileSource-upload ref="upload" :sourceCode="sourceCode" :showFileList="false" @success="handleUploadSuccess"></l-fileSource-upload>
        </l-tool-btns>
      </template>
      <l-table
        ref="mainTable"
        :loading="tableLoading"
        :columns="lr_getPageColumns(columns)"
        :dataSource="tableData"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        @loadPageData="turnTablePage"
      >
        <template v-slot:type="scope">
          <el-tag v-if="scope.row.type == 1">Minio</el-tag>
        </template>
        <l-table-btns
          :btns="tableBtns"
          @click="lr_handleTableBtnClick"
        ></l-table-btns>
      </l-table>
    </l-panel>

    <!--表单-->
    <l-dialog
      :title="$t(formTitle)"
      :visible.sync="formVisible"
      :height="400"
      :width="600"
      @ok="handleSave"
      @close="handleCloseForm"
      @opened="handleOpenedForm"
    >
      <my-form ref="form"></my-form>
    </l-dialog>

  </l-layout>
</template>

<script>
import MyForm from "./form";

const api = window.$api.fileSource.file;
const sourceApi = window.$api.fileSource.source;

export default {
  components: {
    MyForm,
  },
  data() {
    return {
      lr_isPage: true,
      moduleCode: "fileSource_file",

      treeLoading: false,
      sourceCode: '',
      treeData: [],

      // 查询参数
      queryData: {
        name: "",
        sourceId: '',
      },

      queryItems: [
        { label: this.$t("名称"), prop: "name" },
      ],

      // 表格参数
      tableLoading: false,
      tableData: [],
      tableTotal: 0,
      tableCurrentPage: 1,
      tablePageSize: 50,
      columns: [
        { label: "名称", prop: "name", minWidth: 120, align: "left", dataType: "input", },
        { label: "大小", prop: "fileSize", width: 100, dataType: "input", },
      ],
      tableBtns: [
        { prop: "Download", label: this.$t("下载"),width:40 },
        { prop: "Delete", label: this.$t("删除"),width:40 },
      ],

      // 表单参数
      formVisible: false,
      formTitle: "",
      formEditRow: null,
      formEdit: false
    };
  },
  computed: {
    objectId() {
      if (this.formEditRow) {
        return this.formEditRow.id;
      }
      return "";
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.loadSourceData();
      //this.loadTableData();
    },

    async loadSourceData() {
      this.treeData = await this.$awaitWraper(sourceApi.select())
      if(this.treeData && this.treeData.length > 0){
        this.$nextTick(() => {
          this.sourceCode = this.treeData[0].code
          this.queryData.sourceId = this.treeData[0].id
          this.$refs.sourceTree.setCurrentKey(this.treeData[0].id)
          this.loadTableData(true);
        })
      }
    },

    handleSearch() {
      this.loadTableData();
    },

    handleNodeClick(node) {
      this.queryData.sourceId = node.id
      this.sourceCode = node.code
      this.loadTableData(true);
    },

    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTableData(true);
    },
    async loadTableData(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      this.tableLoading = true;
      let queryData = this.$deepClone(this.queryData);

      queryData.rows = this.tablePageSize;
      queryData.page = this.tableCurrentPage;
      queryData.sidx = "Id";
      let data = await this.$awaitWraper(api.getPage(queryData));
      if (data != null) {
        this.tableData = data.rows;
        this.tableTotal = data.records;
      } else {
        this.tableData = [];
      }
      this.tableLoading = false;
    },

    handleAdd() {
      this.formEdit = false;
      this.handleShowForm("新增");

    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.handleShowForm("编辑");
    },
    handleDownload($index, row) {
      api.download(row.id, row.name)
    },
    handleDelete($index, row) {
      this.$confirm(
        this.$t("此操作将永久删除该数据, 是否继续?"),
        this.$t("提示"),
        {
          confirmButtonText: this.$t("确定"),
          cancelButtonText: this.$t("取消"),
          type: "warning",
        }
      )
        .then(async () => {
          this.tableData.splice($index, 1);
          this.tableTotal--;
          await api.remove(row.id);
          this.$message({
            type: "success",
            message: this.$t("删除成功!"),
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("已取消删除!"),
          });
        });
    },

    async handleSave(showLoading, hideLoading) {
      showLoading("保存数据中...");
      if (await this.$refs.form.validateForm()) {
        const res = await this.$refs.form.saveForm({
          keyValue: this.formEdit ? this.formEditRow.id : "",
          isEdit: this.formEdit,
        });
        if (res) {
          const msg = this.formEdit ? this.$t("更新成功!") : this.$t("新增成功!");
          this.$message({
            type: "success",
            message: this.$t(msg),
          });
          this.loadTableData();
          this.formVisible = false;
        }
      }
      hideLoading();
    },

    handleShowForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },
    async handleOpenedForm(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading("加载数据中...");
        await this.$refs.form.loadFormData({ keyValue: this.formEditRow.id });
        hideLoading();
      }
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },

    handleUploadSuccess(response) {
      // this.$notify({
      //   position: 'bottom-right',
      //   title: '文件上传成功',
      //   type: 'success'
      // })
      this.$message({
        type: 'success',
        message: this.$t('文件上传成功')
      })
      this.loadTableData(false)

      this.$refs.upload.$refs.upload.clearFiles()
    }
  },
};
</script>
